package codeanticode.vision;

import java.awt.image.BufferedImage;

import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

import processing.core.PApplet;
import processing.core.PImage;

public class BaseGrabber extends PImage {
  protected Vision vision;
  protected FrameGrabber grabber;
  protected IplImage grabImage;
  protected boolean firstFrame;
  protected boolean usePixels;
  
  public BaseGrabber(PApplet parent) {
    vision = new Vision(parent); 
    usePixels = true;    
  }
  
  public void start() {
    try {
      grabber.start();
    } catch (Exception e) {      
    }
  }
  
  public void stop() {
    try {
      grabber.stop();
    } catch (Exception e) {      
    }  
  }
  
  public boolean read() {
    try {
      grabImage = grabber.grab();
    } catch (Exception e) {
      return false;
    }    
        
    if (firstFrame) {
      int w = grabImage.width();
      int h = grabImage.height();      
      super.init(w, h, RGB);
      loadPixels();
      firstFrame = false;
    }
    
    if (usePixels) {
      BufferedImage img = grabImage.getBufferedImage();
      img.getRGB(0, 0, width, height, pixels, 0, width);
      updatePixels();
    }
    
    return true;
  }
  
  public void usePixels(boolean value) {
    usePixels = value;
  }
}
